<?php

namespace App\Http\Controllers\V1\Upload;

use App\Events\V1\ImportExportEvent;
use App\Http\Requests\V1\ImportDataRequest;
use App\Models\V1\Major;
use App\Models\V1\NewArrival;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Maatwebsite\Excel\Facades\Excel;
USE Log;
use Auth;


class MajorExcelUploadController extends BaseExcelUploadController
{
    /**
     * 导入课程数据
     *
     * @param Request $request
     */
    public function importData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '专业数据导入失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);
            $filePath = $request->input('successFile');

            $arrival_code = $this->getArrivalCode();
            if (empty($arrival_code)) {
                $response['rspStatus'] = false;
                $response['rspMsg'] = '请先启动迎新换届';
                return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
            }
            Excel::load($filePath, function($reader) use ($arrival_code) {
                $reader->limitColumns(6);
                //忽略空的cells
                $data = $reader->ignoreEmpty()->toArray();
                collect($data) -> flatMap(function($item) use ($arrival_code) {
                    $code = $item[0];
                    $insert_data = [
                        'arrival_code' => $arrival_code,
                        'code' => $code,
                        'name' => $item[1],
                        'min_number' => $item[2],
                        'max_number' => $item[3],
                        'count' => $item[4],
                        'parent_code' => $item[5],

                    ];
                    if (!empty($code) && !empty($item[1])) {
                        Major::updateOrCreate(['arrival_code'=>$arrival_code,'code'=>$code],$insert_data);
                    }
                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入['.$request->input('successFile').']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));

            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 导出专业数据文件
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();
//        $header = ['迎新代码','招生目录代码','招生目录(大类专业／方向)名称', '至少填报志愿数', '至多填报志愿数', '专业名称', '专业招生计划人数'];
        $header = ['专业代码', '专业名称', '至少填报志愿数', '至多填报志愿数', '专业招生计划人数','所属专业代码（0:为招生目录）'];
        $arrival_code = $this->getArrivalCode();
        if (empty($arrival_code)) {
            $response['rspStatus'] = false;
            $response['rspMsg'] = '请先启动迎新换届';
            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
        $custodian = Major::where('arrival_code',$arrival_code)->select('code','name','min_number','max_number','count','parent_code')->get();
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            $cellData = [
                $item->code,
                $item->name,
                $item->min_number,
                $item->max_number,
                $item->count,
                $item->parent_code,
            ];
            array_push($cellDatas, $cellData);
        }
        Excel::create('志愿', function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('major', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });
            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[专业]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }


    /****
     * 下载模版
     * @param Request $request
     */
    public function downData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = ['专业代码', '专业名称', '至少填报志愿数', '至多填报志愿数', '专业招生计划人数','所属专业代码（0:为招生目录）'];
        $cellDatas = [$header];
        $cellData1 = ['130000','外语','80','200','','0'];
        $cellData2 = ['130100','英语','','','50','130000'];
        $cellData3 = ['130101','日语','','','40','130000'];
        array_push($cellDatas, $cellData1);
        array_push($cellDatas, $cellData2);
        array_push($cellDatas, $cellData3);
        Excel::create('专业数据导入模版', function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('major', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });
            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[专业]模版文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }

    /***
     * 根据code获取专业信息
     * @param $code
     * @return mixed
     */
    private function getMajorByCode($code)
    {
        $major = Major::where('code', $code)->first();
        return $major;
    }

    /***
     * 获取所有专业数据
     * @param $code
     * @return mixed
     */
    private function getMajors()
    {
        $majors = Major::where('parent_code','!=','0')->get();
        return $majors;
    }

}
